package dao.manager.impl;

import dao.BaseDao;
import dao.manager.AnnouncementDao;
import entity.Announcement;
import entity.Borrow_books;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * AnnouncementDaoImpl
 *
 * @author 谭文斌
 * @since 2023/8/31
 */
public class AnnouncementDaoImpl extends BaseDao implements AnnouncementDao {
    @Override
    public int add(Announcement announcement) {
        String sql="insert announcement values(default,?,?,?)";
        return super.executeUpdate(sql,announcement.getTitle(),announcement.getDetail(),announcement.getPublish_date());
    }

    @Override
    public List<Announcement> getList() {
        List<Announcement> list = new ArrayList<>();
        String sql = "select * from announcement";
        Connection conn=super.getConnection();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps= conn.prepareStatement(sql);
            rs=ps.executeQuery();
            while (rs.next()) {
                Announcement a=new Announcement();
                a.setId(rs.getInt("id"));
                a.setTitle(rs.getString("title"));
                a.setDetail(rs.getString("detail"));
                a.setPublish_date(rs.getString("publish_date"));
                list.add(a);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(rs,ps,conn);
        }
        return list;
    }

    @Override
    public int del(int id) {
        String sql="delete from announcement where id=?";
        return super.executeUpdate(sql,id);
    }

    @Override
    public int upd(Announcement announcement) {
        String sql = "update announcement set title=?,detail=? where id=?";
        return super.executeUpdate(sql, announcement.getTitle(),announcement.getDetail(),announcement.getId());
    }

    @Override
    public Announcement getId(int id) {
        Announcement a=null;
        String sql = "select * from announcement where id=?";
        Connection conn=super.getConnection();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps= conn.prepareStatement(sql);
            ps.setInt(1, id);
            rs=ps.executeQuery();
            while (rs.next()) {
                a=new Announcement();
                a.setId(rs.getInt("id"));
                a.setTitle(rs.getString("title"));
                a.setDetail(rs.getString("detail"));
                a.setPublish_date(rs.getString("publish_date"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(rs,ps,conn);
        }
        return a;
    }
}
